<!DOCTYPE HTML>
<html>
    <head>
        <title>用parseInt解析数字并求和</title>
        <mate charset="utf-8" />
        <style type="text/css">
        *{ padding: 0px; margin: 0px; text-align: center; }
        .cpp1{ margin: 30px auto; font-size: 20px; }
        .cpp1 span, .cpp1 input{ margin: 0px 5px 0px 5px; }
        .cpp1 input{ width: 200px; height: 30px; }
        .cpp1 button{ width: 50px; height: 34px; margin-left: 10px; }
        .cpp1 strong{ color: green; }
        </style>
    </head>
    <body>
        <div class="cpp1">
            <input type="text" />
            <span>+</span>
            <input type="text" />
            <span>=</span>
            <strong>?</strong>
            <button>求和</button>
        </div>
 
        <script type="text/javascript">
            window.onload = function(){
                // 获取元素
                var inputext = document.getElementsByClassName("cpp1")[0].getElementsByTagName("input");
                var sumbtn = document.getElementsByClassName("cpp1")[0].getElementsByTagName("button")[0];
                // 遍历事件
                for(var i = 0; i < inputext.length; i++){
                    // 键盘松开事件
                    inputext[i].onkeyup = function(){
                        // 将文本框中非整数替换
                        this.value = this.value.replace(/[^\d]/, "");
                    }
                }
                // 求和按钮点击事件
                sumbtn.onclick = function(){
                    if(inputext[0].value == "" || inputext[1].value == "")
                        alert("请输入数字！");
                    else
                        document.getElementsByTagName("strong")[0].innerHTML = parseInt(inputext[0].value) + parseInt(inputext[1].value);
                }
            }
        </script>
    </body>